package com.woniuxy.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.admin.exception.AdminException;
import com.woniuxy.admin.entity.AdminRole;
import com.woniuxy.admin.entity.Menu;
import com.woniuxy.admin.entity.RoleMenu;
import com.woniuxy.admin.mapper.AdminRoleMapper;
import com.woniuxy.admin.mapper.MenuMapper;
import com.woniuxy.admin.mapper.RoleMenuMapper;
import com.woniuxy.admin.service.RoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ...
 * @since 2024年05月22日
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {


    @Resource
    private MenuMapper menuMapper;
    @Resource
    private AdminRoleMapper adminRoleMapper;

    /**
     * 绑定角色和菜单
     * @param menuIds 菜单id
     * @param roleId 角色id
     */
    @Override
    public void bindingRoleMenu(List<Integer> menuIds, Integer roleId) {
        AdminRole adminRole = adminRoleMapper.selectById(roleId);
        if(adminRole==null) throw new AdminException(10007,"角色不存在");
        List<Menu> menus = menuMapper.selectList(new QueryWrapper<Menu>());
        if (!menus.stream().map(m->m.getId()).collect(Collectors.toList()).containsAll(menus)) {
            throw new AdminException(10008,"有菜单不存在");
        }
        QueryWrapper<RoleMenu>wrapper=new QueryWrapper<>();
        wrapper.eq("role_id",roleId);
        List<RoleMenu> roleMenus = this.list(wrapper);
        if(roleMenus!=null&&roleMenus.size()>0){
            for (RoleMenu roleMenu : roleMenus) {
                for (Integer menuId : menuIds) {
                    if(roleMenu.getMenuId()==menuId){
                        throw new AdminException(10000,"该角色已有所选菜单");
                    }
                }
            }
        }
        List<RoleMenu>list=new ArrayList<>();
        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(roleId);
            list.add(roleMenu);
        }
        this.saveBatch(list);
    }
}
